package com.pd.modules.rmiobserver;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observer;

import com.pd.modules.common.Room;
import com.pd.modules.common.rmi.IRemoteDatabaseObserver;
import com.pd.modules.common.rmi.IRemoteDatabaseServer;

@SuppressWarnings("serial")
public class RemoteDatabaseObserver extends UnicastRemoteObject implements IRemoteDatabaseObserver {

	private String mStartDate;
	private String mEndDate;

	private List<Room> mRooms = null;

	IRemoteDatabaseServer mRemoteServer = null;

	List<Observer> mObservers = new ArrayList<Observer>();

	public boolean mIsConnected = false;
	public RemoteDatabaseObserver(String _ip, String _startDateTime, String _endDateTime) throws ParseException, RemoteException, MalformedURLException, NotBoundException {
		mStartDate = _startDateTime;
		mEndDate = _endDateTime;
		mRemoteServer = (IRemoteDatabaseServer) Naming.lookup("rmi://" + _ip + "/DatabaseChangeNotifier");
	
		mRemoteServer.registerObserver(this);
		
		mIsConnected = true;
	}

	public void setObservedInterval(String _startDateTime, String _endDateTime) throws ParseException
	{
		mStartDate = _startDateTime;
		mEndDate = _endDateTime;

		try
		{
			getAvailableRooms(true);

			for (Observer o : mObservers)
				o.update(null, null);

		} catch (RemoteException e)
		{
			e.printStackTrace();
		}
	}

	public void addObserver(Observer _obs)
	{
		mObservers.add(_obs);
	}

	@Override
	public void onChangeOccurred(List<String> _availableRooms) throws RemoteException
	{
		mRooms.clear();
		for (String r : _availableRooms)
			mRooms.add(new Room(r));

		for (Observer o : mObservers)
			o.update(null, null);
	}

	@Override
	public String getStartDate() throws RemoteException
	{

		return mStartDate;
	}

	@Override
	public String getEndDate() throws RemoteException
	{
		return mEndDate;
	}


	synchronized public List<Room> getAvailableRooms(boolean _forceUpdate) throws RemoteException
	{
		if (null == mRooms || _forceUpdate)
		{
			mRooms = new ArrayList<Room>();

			List<String> rooms = mRemoteServer.getAvailableRooms(mStartDate, mEndDate);
			for (String r : rooms)
				mRooms.add(new Room(r));

		}

		return mRooms;
	}

	@Override
	public void disconnect() throws RemoteException
	{
		mIsConnected = false;
		
		for (Observer o : mObservers)
			o.update(null, null);
	}

}
